<template>
	<form-item-wrapper :designer="designer" :field="thisField" :rules="rules" :design-state="thisDesignState"
					   :parent-widget="thisParentWidget" :parent-list="thisParentList" :index-of-parent-list="thisIndexOfParentList" :style="field.options.customStyle"
					   :sub-form-row-index="thisSubFormRowIndex" :sub-form-col-index="thisSubFormColIndex" :sub-form-row-id="thisSubFormRowId">
		<el-input ref="fieldEditor" v-model="fieldModel"
				  :disabled="field.options.disabled" :readonly="thisField.options.readonly"
				  :size="widgetSize" class="hide-spin-button"
				  :type="inputType"
				  :show-password="thisField.options.showPassword"
				  :placeholder="thisField.options.placeholder"
				  :clearable="thisField.options.clearable"
				  :minlength="thisField.options.minLength" :maxlength="thisField.options.maxLength"
				  :show-word-limit="thisField.options.showWordLimit"
				  :prefix-icon="thisField.options.prefixIcon" :suffix-icon="thisField.options.suffixIcon"
				  @focus="handleFocusCustomEvent" @blur="handleBlurCustomEvent" @input="handleInputCustomEvent"
				  @change="handleChangeEvent">
			<template #append v-if="thisField.options.appendButton||thisField.options.appendText">
				<el-button v-if="thisField.options.appendButton" :disabled="thisField.options.disabled || thisField.options.appendButtonDisabled"
						   @click="emitAppendButtonClick">
					<el-icon style="vertical-align: -0.15em;height: 1.1em;width: 1.1em">
						<component :is="thisField.options.buttonIcon" style="height: 1.1em;width: 1.1em"/>
					</el-icon>
				</el-button>
				<span v-if="thisField.options.appendText">
					{{thisField.options.suffixText}}
				</span>
			</template>
		</el-input>
	</form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import fieldMixin from "@/components/designer/form-designer/form-widget/field-widget/fieldMixin";

export default {
	name: "input-calculation-widget",
	componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
	mixins: [emitter, fieldMixin],
	props: {
		field: Object,
		parentWidget: Object,
		parentList: Array,
		indexOfParentList: Number,
		designer: Object,
		designState: {
			type: Boolean,
			default: false
		},
		subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
			type: Number,
			default: -1
		},
		subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
			type: Number,
			default: -1
		},
		subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
			type: String,
			default: ''
		},
	},
	components: {
		FormItemWrapper,
	},
	data() {
		return {
			bindEls:[],
			thisField: this.field,
			thisParentWidget: this.parentWidget,
			thisParentList:this.parentList,
			thisIndexOfParentList:this.indexOfParentList,
			thisDesignState:this.designState,
			thisSubFormRowIndex:this.subFormRowIndex,
			thisSubFormColIndex:this.subFormColIndex,
			thisSubFormRowId:this.subFormRowId,
			oldFieldValue: null, //field组件change之前的值
			fieldModel: null,
			rules: [],
			bindFields:[],
			formulaType:'',
			formula:'',
			resFormula:'',
		}
	},
	computed: {
		inputType() {
			if (this.thisField.options.type === 'number') {
				return 'text'  //当input的type设置为number时，如果输入非数字字符，则v-model拿到的值为空字符串，无法实现输入校验！故屏蔽之！！
			}
			return this.thisField.options.type
		},
		getBindElsFieldModel()
		{
			let arr=[];
			this.bindEls.forEach(item=>{
				let name = item.thisField.options.name;
				let json = {};
				json[name] = item.fieldModel;
				arr.push(json);
			})
			return arr;
		}
	},
	watch: {
		"getBindElsFieldModel":{
			deep: true,
			immediate: true, // 是否初始化时就执行一次
			handler(val,old)
			{
				try {
					let tempFormula = this.resFormula;
					if (this.formulaType == "RMB") {
						val.forEach(item => {
							for (var key in item) {
								let v = '0';
								if (item[key] != '') {
									v = item[key]
								}
								tempFormula = tempFormula.replace("{" + key + "}", v);
							}
						})
						let res = eval("(" + tempFormula + ")");
						this.fieldModel = this.RMB(res);
					} else if (this.formulaType == 'DAY' || this.formulaType == 'HOUR' || this.formulaType == 'DATE' || this.formulaType == 'YEAR') {
						let optValArr = [];
						val.forEach(item => {
							for (var key in item) {
								if (item[key] != '') {
									optValArr.push(item[key])
								} else {
									optValArr.push("")
								}
							}
						})
						if (this.formulaType == 'DAY') {
							this.fieldModel = this.DAY(optValArr[0], optValArr[1]);
						} else if (this.formulaType == 'HOUR') {
							this.fieldModel = this.HOUR(optValArr[0], optValArr[1]);
						} else if (this.formulaType == 'DATE') {
							this.fieldModel = this.DATE(optValArr[0], optValArr[1]);
						} else if (this.formulaType == 'YEAR') {
							this.fieldModel = this.YEAR(optValArr[0], optValArr[1]);
						}
					} else if (this.formulaType == 'AVG' || this.formulaType == 'MAX' || this.formulaType == 'MIN') {
						let optValArr = [];
						val.forEach(item => {
							for (var key in item) {
								if (item[key] != '') {
									optValArr.push(item[key])
								} else {
									optValArr.push("")
								}
							}
						})
						if (this.formulaType == 'AVG') {
							this.fieldModel = this.AVG(optValArr);
						} else if (this.formulaType == 'MAX') {
							this.fieldModel = this.MAX(optValArr);
						} else if (this.formulaType == 'MIN') {
							this.fieldModel = this.MIN(optValArr);
						}
					} else if (this.formulaType == 'ABS') {
						let v = '0';
						val.forEach(item => {
							for (var key in item) {
								if (item[key] != '') {
									v = item[key]
								}
							}
						})
						this.fieldModel = this.ABS(v);
					} else {
						val.forEach(item => {
							for (var key in item) {
								let v = '0';
								if (item[key] != '') {
									v = item[key]
								}
								tempFormula = tempFormula.replace("{" + key + "}", v);
							}
						})
						let res = eval(tempFormula);
						this.fieldModel = res;
					}
				}catch (e)
				{
					this.fieldModel = "????";
				}
			},
		},
		"fieldModel":{
			handler(val)
			{
				this.handleChangeEvent(val)
			}
		},
		'field.options.formula':{
			handler()
			{
				this.initFormulaType()
			}
		},
	},
	beforeCreate() {
		/* 这里不能访问方法和属性！！ */
	},

	created() {
		/* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
		   需要在父组件created中初始化！！ */
		this.initFieldModel()
		this.registerToRefList()
		this.initEventHandler()
		this.buildFieldRules()

		this.handleOnCreated()
	},

	mounted() {
		this.handleOnMounted();
		this.initFormulaType()
	},

	beforeUnmount() {
		this.unregisterFromRefList()
	},

	methods: {
		initFormulaType(){
			this.bindEls = [];
			this.formula=this.thisField.options.formula;
			if (this.formula.indexOf("RMB") > -1) {
				this.formulaType="RMB"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else if (this.formula.indexOf("DAY") > -1) {
				this.formulaType="DAY"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else if (this.formula.indexOf("HOUR") > -1) {
				this.formulaType="HOUR"
				this.resFormula = this.formula.substring(5,(this.formula.length)-1);
			}else if (this.formula.indexOf("DATE") > -1) {
				this.formulaType="DATE"
				this.resFormula = this.formula.substring(5,(this.formula.length)-1);
			}else if (this.formula.indexOf("YEAR") > -1) {
				this.formulaType="YEAR"
				this.resFormula = this.formula.substring(5,(this.formula.length)-1);
			}else if(this.formula.indexOf("AVG") > -1) {
				this.formulaType="AVG"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else if(this.formula.indexOf("MAX") > -1) {
				this.formulaType="MAX"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else if(this.formula.indexOf("MIN") > -1) {
				this.formulaType="MIN"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else if(this.formula.indexOf("ABS") > -1) {
				this.formulaType="ABS"
				this.resFormula = this.formula.substring(4,(this.formula.length)-1);
			}else
			{
				this.resFormula = this.thisField.options.formula;
			}
			try {
				let regExp=new RegExp("(\\{)(.+?)(?=\\})",'g');
				let tempFields = this.formula.match(regExp);
				if(tempFields!=null)
				{
					tempFields.forEach(item=>{
						this.bindFields.push(item.replace("{",'').replace("}",''))
					})
					this.bindFields.forEach(item=>{
						this.bindEls.push(this.refList[item]);
					})
				}
			}catch (e)
			{
				console.log(e)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
@import "../../../../../assets/formdesigner/styles/global.scss"; /* form-item-wrapper已引入，还需要重复引入吗？ */

</style>
